from django.db.models import Q
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.decorators import action
from rest_framework.mixins import UpdateModelMixin

from orders.models import OrderInfo
from ..serializers.orders import OrderListSerializer, OrderDetailSerializer, OrderStatusSerializer


# GET /meiduo_admin/orders/?keyword=<搜索内容>&page=<页码>&pagesize=<页容量>
class OrdersViewSet(UpdateModelMixin, ReadOnlyModelViewSet):
    permission_classes = [IsAdminUser]

    def get_serializer_class(self):
        """返回视图所使用的序列化器类"""
        if self.action == 'list':
            return OrderListSerializer
        elif self.action == 'retrieve':
            return OrderDetailSerializer
        else:
            return OrderStatusSerializer

    def get_queryset(self):
        # 获取搜索关键字
        keyword = self.request.query_params.get('keyword')

        if not keyword:
            orders = OrderInfo.objects.all()
        else:
            orders = OrderInfo.objects.filter(Q(order_id=keyword) |
                                              Q(skus__sku__name__contains=keyword))

        return orders

    # PUT /meiduo_admin/orders/(?P<pk>\d+)/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """修改订单状态"""
        return self.update(request, pk)
